package org.jeecg.modules.product.risk.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.product.risk.entity.TbBaseCheckRecord;
import org.jeecg.modules.product.risk.entity.TbBaseCheckTask;
import org.jeecg.modules.product.risk.service.ITbBaseCheckRecordService;
import org.jeecg.modules.product.risk.service.ITbBaseCheckTaskService;
import org.jeecg.modules.product.riskUnit.entity.TbBaseRiskDevice;
import org.jeecg.modules.product.riskUnit.service.ITbBaseRiskDeviceService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 专项检查任务表
 * @Author: jeecg-boot
 * @Date:   2024-05-08
 * @Version: V1.0
 */
@Tag(name="专项检查任务表")
@RestController
@RequestMapping("/TbBaseCheckTask/tbBaseCheckTask")
@Slf4j
public class TbBaseCheckTaskController extends JeecgController<TbBaseCheckTask, ITbBaseCheckTaskService> {
	@Autowired
	private ITbBaseCheckTaskService tbBaseCheckTaskService;
	 @Autowired
	 private ITbBaseCheckRecordService tbBaseCheckRecordService;
	 @Autowired
	 private ITbBaseRiskDeviceService baseRiskDeviceService;

	/**
	 * 分页列表查询
	 *
	 * @param tbBaseCheckTask
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "专项检查任务表-分页列表查询")
	@Operation(summary="专项检查任务表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(TbBaseCheckTask tbBaseCheckTask,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<TbBaseCheckTask> queryWrapper = QueryGenerator.initQueryWrapper(tbBaseCheckTask, req.getParameterMap());
		Page<TbBaseCheckTask> page = new Page<TbBaseCheckTask>(pageNo, pageSize);
		queryWrapper.eq("deleted","0");
		IPage<TbBaseCheckTask> pageList = tbBaseCheckTaskService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param tbBaseCheckTask
	 * @return
	 */
	@AutoLog(value = "专项检查任务表-添加")
	@Operation(summary="专项检查任务表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody TbBaseCheckTask tbBaseCheckTask) {
		tbBaseCheckTask.setId(UUID.randomUUID().toString());
		tbBaseCheckTaskService.save(tbBaseCheckTask);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param tbBaseCheckTask
	 * @return
	 */
	@AutoLog(value = "专项检查任务表-编辑")
	@Operation(summary="专项检查任务表-编辑")
	@PostMapping(value = "/edit")
	public Result<?> edit(@RequestBody TbBaseCheckTask tbBaseCheckTask) {
		tbBaseCheckTaskService.updateById(tbBaseCheckTask);
		return Result.OK("编辑成功!");
	}

	 /**
	  *  专项检查任务确认
	  *
	  * @param tbBaseCheckTask
	  * @return
	  */
	 @AutoLog(value = "专项检查任务表-确认完成")
	 @Operation(summary="专项检查任务表-确认完成")
	 @PostMapping(value = "/editStatusById")
	 @Transactional
	 public Result<?> editStatusById(@RequestBody TbBaseCheckTask tbBaseCheckTask) {
		 //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		 UpdateWrapper<TbBaseCheckTask> updateWrapper = new UpdateWrapper<>();
//		 updateWrapper.eq("id",tbBaseCheckTask.getId());
//		 updateWrapper.set("finsh_time", DateUtils.now());
//		 tbBaseCheckTaskService.update(updateWrapper);
		 //String currDateTime = DateUtils.now();
		 tbBaseCheckTask.setFinshTime(DateUtils.getDate());
		 boolean flag = tbBaseCheckTaskService.updateById(tbBaseCheckTask);
		 List<TbBaseCheckRecord> list = tbBaseCheckRecordService.list(new QueryWrapper<TbBaseCheckRecord>().eq("task_id",tbBaseCheckTask.getId()));
		 /*----这里需要根据任务id查询匹配到的排查记录数据，并修改记录状态，如果没有记录数据标识可能是非企业自查数据就需要创建一条记录数据---------------------*/
		 if (!list.isEmpty()){
			for (TbBaseCheckRecord tbBaseCheckRecord : list){
				tbBaseCheckRecord.setResultStatus(tbBaseCheckTask.getEnterpriseStatus());
			}
			 tbBaseCheckRecordService.updateBatchById(list);
		 }else {
			 QueryWrapper<TbBaseRiskDevice> queryWrapperDevice = new QueryWrapper<>();
			 queryWrapperDevice.eq("deleted" ,"0");
			 queryWrapperDevice.in("hazard_level","seriousHazard01","seriousHazard02","seriousHazard03","seriousHazard04");
			 List<TbBaseRiskDevice> deviceListList = baseRiskDeviceService.list(queryWrapperDevice);
			 for (TbBaseRiskDevice device: deviceListList){
				 TbBaseCheckRecord record = new TbBaseCheckRecord();
				 record.setId(UUID.randomUUID().toString());
				 record.setTaskId(tbBaseCheckTask.getId());
				 record.setCompanyCode(device.getCompanyCode());
				 record.setHazardCode(device.getHazardCode());
				 record.setCheckType(tbBaseCheckTask.getInspectTypeName());
				 record.setCheckDate(DateUtils.getDate());
				 record.setResultStatus(tbBaseCheckTask.getEnterpriseStatus());
				 tbBaseCheckRecordService.save(record);
			 }
		 }

		 if (flag){
			 return Result.OK("专项检查任务确认完成!");
		 }else {
			 return Result.error("专项检查任务确认失败!");
		 }
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "专项检查任务表-通过id删除")
	@Operation(summary="专项检查任务表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		tbBaseCheckTaskService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "专项检查任务表-批量删除")
	@Operation(summary="专项检查任务表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tbBaseCheckTaskService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	 /**
	  *   通过id逻辑删除
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "专项检查任务表-通过id逻辑删除")
	 @Operation(summary="专项检查任务表-通过id逻辑删除")
	 @DeleteMapping(value = "/logicDelete")
	 public Result<?> logicDelete(@RequestParam(name="id",required=true) String id) {
		 TbBaseCheckTask tbBaseCheckTask = tbBaseCheckTaskService.getById(id);
		 tbBaseCheckTask.setDeleted("1");//禁止状态1是已删除，0是正常未删除
		 tbBaseCheckTaskService.updateById(tbBaseCheckTask);
		 return Result.OK("删除成功!");
	 }

	 /**
	  *  批量逻辑删除
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "专项检查任务表-批量逻辑删除")
	 @Operation(summary="专项检查任务表-批量逻辑删除")
	 @DeleteMapping(value = "/deleteLogicBatch")
	 public Result<?> deleteLogicBatch(@RequestParam(name="ids",required=true) String ids) {
		 List<TbBaseCheckTask> list = tbBaseCheckTaskService.listByIds(Arrays.asList(ids.split(",")));
		 for (TbBaseCheckTask tbBaseCheckTask : list) {
			 tbBaseCheckTask.setDeleted("1");//禁止状态1是已删除，0是正常未删除
		 }
		 tbBaseCheckTaskService.updateBatchById(list);
		 return Result.OK("批量删除成功！");
	 }

	 /**
	  * 获取被逻辑删除的专项检查任务表
	  *
	  * @return logicDeletedUserList
	  */
	 @GetMapping("/recycleBin")
	 public Result getRecycleBin(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		 QueryWrapper<TbBaseCheckTask> queryWrapper = new QueryWrapper<>();
		 queryWrapper.eq("deleted", "1");//查询已经删除的数据
		 Page<TbBaseCheckTask> page = new Page<TbBaseCheckTask>(pageNo, pageSize);
		 IPage<TbBaseCheckTask> pageList = tbBaseCheckTaskService.page(page, queryWrapper);
		 return Result.ok(pageList);
	 }

	 /**
	  * 还原被逻辑删除的专项检查任务表
	  *
	  * @param jsonObject
	  * @return
	  */
	 @RequestMapping(value = "/putRecycleBin", method = RequestMethod.PUT)
	 public Result putRecycleBin(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
		 String tbBaseCheckTaskIds = jsonObject.getString("tbBaseCheckTaskIds");
		 if (StringUtils.isNotBlank(tbBaseCheckTaskIds)) {
			 List<TbBaseCheckTask> list = tbBaseCheckTaskService.listByIds(Arrays.asList(tbBaseCheckTaskIds.split(",")));
			 for (TbBaseCheckTask entity : list) {
				 entity.setDeleted("0");
			 }
			 tbBaseCheckTaskService.updateBatchById(list);
		 }
		 return Result.ok("还原成功");
	 }
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "专项检查任务表-通过id查询")
	@Operation(summary="专项检查任务表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		TbBaseCheckTask tbBaseCheckTask = tbBaseCheckTaskService.getById(id);
		if(tbBaseCheckTask==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(tbBaseCheckTask);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param tbBaseCheckTask
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TbBaseCheckTask tbBaseCheckTask) {
        return super.exportXls(request, tbBaseCheckTask, TbBaseCheckTask.class, "专项检查任务表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TbBaseCheckTask.class);
    }

	 /**
	  * 通过id任务分解
	  *
	  * @param baseCheckTask
	  * @return
	  */
	 @AutoLog(value = "专项检查任务表-通过id任务分解")
	 @Operation(summary="专项检查任务表-通过id任务分解")
	 @GetMapping(value = "/taskDecomposition")
	 public Result<?> taskDecompositionById(TbBaseCheckTask baseCheckTask) {
		 int count = tbBaseCheckTaskService.taskDecomposition(baseCheckTask);
		 if(count > 0) {
			 return Result.OK("任务分解成功，请移步到'检查计划'中进行后续操作,完成检查后请回到此处进行任务完成确认!成功条数为:"+count);
		 }else {
			 return Result.error("任务分解失败，请重试!");
		 }
	 }

}
